<template>
  <div class="index">
    <div class="context">
      <h2>后台管理系统</h2>
      <div class="text">
        <div class="innerBox">
          <el-input class="input" v-model="userName" placeholder="请输入用户名"></el-input>
          <el-input class="input" placeholder="请输入密码" v-model="password" show-password></el-input>
        </div>
        <el-button type="primary" class="btn" @click="sendMsg">登录</el-button>
      </div>
      <router-link to="/register">
        <el-link type="info" class="loginBtn">去注册</el-link>
      </router-link>
    </div>
  </div>
</template>

<script>

import { userLogin } from '@/api'

export default {
  name: 'my-login',
  data () {
    return {
      userName: localStorage.getItem('userName'),
      password: localStorage.getItem('password')
    }
  },
  methods: {
    async sendMsg () {
      if (localStorage.getItem('token')) {
        // 重复登录提醒
        this.$message.error('请不要重复登录')
        setTimeout(() => {
          this.$router.push('/')
        }, 1000)
      } else {
        const data = {
          username: this.userName,
          password: this.password
        }
        // 发送请求
        const res = await userLogin(data)
        if (res.data.code === 1) {
          this.$message.error('登录失败')
        } else if (res.data.code === 0) {
          await this.$store.commit('SAVETOKEN', res.data.token)
          localStorage.setItem('token', res.data.token)
          this.$message.success('登录成功')
          setTimeout(() => {
            this.$router.push('/')
          }, 1000)
          localStorage.setItem('userName', this.userName)
          localStorage.setItem('password', this.password)
        } else if (res.data.code === 2) {
          this.$message.error('不能为空')
        }
      }
    }
  }
}
</script>

<style scoped>
*{
  margin: 0;
  padding: 0;
}
.index{
  height: 100%;
  width: 100%;
  background: url('../../assets/images/login_bg.jpg') no-repeat;
  overflow: hidden;
  background-size: cover;
}
.context{
  width: 400px;
  height: 300px;
  margin: 310px auto;
  background-color: white;
  border-radius: 3px;
}
.context h2{
  text-align: center;
  color: deepskyblue;
  line-height: 50px;
}
.text{
  width: 100%;
  height: 230px;
  position: relative;
}
.btn{
  width: 200px;
  height: 40px;
  position: absolute;
  bottom: 20px;
  left: 100px;
}
.innerBox{
  position: absolute;
  left: 15px;
  top:30px;
}
.input{
  width: 370px;
  margin-top: 10px;
}
.loginBtn{
  position: relative;
  left: 176px;
  bottom: 20px;
  font-size: 15px;
}
</style>
